package com.eureka.provider.queue.jvm;/*
 *@Description
 *@Author:Sam
 *@creat-time:2021/4/20 10:18
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eureka.provider.mapper.OrderMapper;
import com.eureka.provider.pojo.Order;
import com.eureka.provider.pojo.SeckillGoods;
import com.eureka.provider.service.IGoodsService;
import com.eureka.provider.service.ISeckillGoodsService;
import com.eureka.provider.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class SeckillQueueCunsumer implements ApplicationRunner {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    ISeckillGoodsService seckillGoodsService;
    @Override
    @Transactional
    public void run(ApplicationArguments applicationArguments) throws Exception {
        new Thread(()->{
           while(true){
               try {
                   Order order = SeckillQueue.getSkillQueue().consume();
                   GoodsVo goods = goodsService.findGoodsVoById(order.getGoodsId());
                   if(goods.getSeckillStock()<1){
                       //log.info("库存不足");
                       return;
                   }
                   //更新库存
                   SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>()
                           .eq("goods_id", goods.getId()));
                   seckillGoods.setSeckillStock(seckillGoods.getSeckillStock()-1);
                   seckillGoodsService.updateById(seckillGoods);
                   int insert = orderMapper.insert(order);
                   if(insert==1){
                       log.info("订单生成成功："+order.toString());
                   }
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        }).start();
    }
}
